package srp

import (
    `net/http`
    `encoding/json`
    `strconv`
)

// 将功能单一化

func loadUserHandlerSRP(w http.ResponseWriter, r *http.Request) {
    userID, err := extractIDFromRequest(r)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    person, err := loadPersonByID(userID)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    outputPerson(w, person)

}
func extractIDFromRequest(r *http.Request) (int64, error) {
    err := r.ParseForm()
    if err != nil {
        return 0, err
    }
    return strconv.ParseInt(r.Form.Get("UserID"), 10, 64)

}

func loadPersonByID(userId int64) (*Person, error) {
    row := DB.QueryRow("SELECT * FROM Users WHERE userID = ?", userId)

    person := &Person{}
    err := row.Scan(person.ID, person.Name, person.Phone)
    if err != nil {
        return nil, err
    }

    return person, nil

}

func outputPerson(w http.ResponseWriter, p *Person) {
    encoder := json.NewEncoder(w)
    err := encoder.Encode(p)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
}
